package cn.easybuy.servlet.product;

import cn.easybuy.entity.Product;
import cn.easybuy.service.ProductService;
import cn.easybuy.service.impl.ProductServiceImpl;
import cn.easybuy.util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/productAddServlet")
public class ProductAddUpdServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            Map<String,String> map = new HashMap<>();
            FileUtil.fileUpload(req,map);
            String id = map.get("id");
            boolean flag= true;
            if(id!=null && !"".equals(id.trim())){
                flag=false;
            }

            int categoryLevel1Id = Integer.parseInt(map.get("categoryLevel1Id"));
            int categoryLevel2Id = Integer.parseInt(map.get("categoryLevel2Id"));
            int categoryLevel3Id = Integer.parseInt(map.get("categoryLevel3Id"));
            String name = map.get("name");
            String photo = map.get("newName");
            float price = Float.parseFloat(map.get("price"));
            int stock = Integer.parseInt(map.get("stock"));
            String description = map.get("description");

            int i=0;
            if(flag){//新增
                Product product = new Product(name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,photo);
                 i = productService.productAdd(product);
            }else{//修改
                Product product = new Product(Integer.parseInt(id),name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,photo);
                 i = productService.productUpd(product);
            }

            if (i>0) {
                req.getRequestDispatcher("/productAllServlet?pageNo=1").forward(req,resp);
            }else {
                System.out.println("失败");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
